package com.rookie.data.generate.exception;



import com.rookie.data.generate.constant.ResponseResult;
import com.rookie.data.generate.constant.enums.ResultCodeEnum;
import com.rookie.data.generate.util.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;


@Slf4j
@RestControllerAdvice
public class CustomerExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public ResponseResult<String> defaultErrorHandler(HttpServletRequest req, Exception e) {
        String errorMsg = "Internal Server Error :" + e.getMessage();
        log.error(errorMsg);
        e.printStackTrace();
        return ResultUtils.error(errorMsg);
    }

    /**
     * GET/POST/DELETE/PUT请求方法错误的拦截器
     * 所以定义了这个拦截器
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ResponseResult<String> httpRequestMethodHandler(HttpRequestMethodNotSupportedException e) {
        log.error("GET/POST/DELETE/PUT请求方式错误", e);
        e.printStackTrace();
        return ResultUtils.error(ResultCodeEnum.E_500);
    }


    /**
     * 控制器接受用户参数，参数绑定时发生异常
     */
    @ExceptionHandler(BindException.class)
    public ResponseResult<String> bindExceptionHandler(BindException e) {
        log.error("参数绑定错误",e);
        e.printStackTrace();
        return ResultUtils.error(Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage());
    }


    /**
     * 实体类校验失败异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult<String> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        log.error("参数校验错误",e);
        e.printStackTrace();
        return ResultUtils.error(Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage());
    }

}
